package com.pxdp.utils;

import cn.hutool.core.lang.UUID;
import io.netty.util.internal.StringUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    private StringRedisTemplate stringRedisTemplate;

    private String name;

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    private static final String LOCK_REDIS = "lock:";

    private static final String ID_PREFIX = UUID.fastUUID().toString(true);

    /**
     * 使用spring自带的类加载lua脚本文件
     */
    private static final DefaultRedisScript<Long> REDIS_SCRIPT ;
    //将加载类放到静态代码块中 启动项目时会跟着类一起加载，减少IO操作
    static{
        REDIS_SCRIPT = new DefaultRedisScript<>();
        //设置脚本加载路径
        REDIS_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        //设置返回值类型
        REDIS_SCRIPT.setResultType(Long.class);
    }

    @Override
    public boolean tryLock(long timeLock){
        //生成一个随机value
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        //利用reids的setnx来创建一个锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_REDIS + name, threadId, timeLock, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unLock(){
        /*String threadId = ID_PREFIX + Thread.currentThread().getId();
        //获取锁里的value
        String id = stringRedisTemplate.opsForValue().get(LOCK_REDIS + name);
        //将锁中的value进行比较
        if(id.equals(threadId)){
            stringRedisTemplate.delete(LOCK_REDIS+name);
        }*/

        //调用lua脚本
        stringRedisTemplate.execute(
                REDIS_SCRIPT,
                Collections.singletonList(LOCK_REDIS+name),
                ID_PREFIX + Thread.currentThread().getId());

    }
}
